package org.rainbowinverted.charging.device.connect.ykc.server.handler;

import org.rainbowinverted.charging.device.connect.ykc.server.message.in.YkcChargeStandardCheckIn;
import org.rainbowinverted.charging.device.connect.ykc.server.message.in.YkcMessageIn;
import org.rainbowinverted.charging.device.connect.ykc.server.message.out.YkcChargeStandardCheckOut;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 计费标准验证器
 * @author hehuaiping
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class YkcChargeStandardCheckHandler extends YkcAbstractHandler<YkcChargeStandardCheckIn, YkcChargeStandardCheckOut>{
    @Override
    public void read(ChannelHandlerContext channel, YkcMessageIn message) {
        ByteBuf messageBody = message.getMessageBody();
        Long deviceNo = readDeviceNo(messageBody);
        YkcChargeStandardCheckIn chargeStandardCheckIn = new YkcChargeStandardCheckIn(deviceNo,
                (int) messageBody.readShort());
        log.info("charge standard check in : {}", chargeStandardCheckIn);
        channel.writeAndFlush(new YkcChargeStandardCheckOut(message.getFrameSerialNo(), deviceNo,
                chargeStandardCheckIn.getChargeStandardModelNo(), Boolean.TRUE));
    }

    @Override
    public void write(ByteBuf byteBuf, YkcChargeStandardCheckOut ykcChargeStandardCheckOut) {
        writeDeviceNo(byteBuf, ykcChargeStandardCheckOut.getDeviceNo());
        // 计费模式编号
        byteBuf.writeShort(ykcChargeStandardCheckOut.getChargeStandardModelNo());
        // 验证结果
        byteBuf.writeByte(ykcChargeStandardCheckOut.getAck() ? 0x00 : 0x01);
    }
}
